package com.rayson.yututu.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.rayson.yututu.common.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Author: rayson
 * Description: 全局异常处理类
 * Version: 1.0
 * Date: 2024-12-16 21:02
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(NotLoginException.class)
    public BaseResponse<?> notLoginExceptionHandler(NotLoginException e) {
        log.error("未登录异常：{}", e.getMessage(), e);
        return BaseResponse.fail(ErrorCodeEnum.NOT_LOGIN);
    }

    @ExceptionHandler(NotPermissionException.class)
    public BaseResponse<?> notPermissionExceptionHandler(NotPermissionException e) {
        log.error("权限不足异常：{}", e.getMessage(), e);
        return BaseResponse.fail(ErrorCodeEnum.NO_AUTH);
    }

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        return BaseResponse.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> methodArgumentNotValidException(MethodArgumentNotValidException exception) {
        log.error("参数校验异常：{}", exception.getMessage(), exception);
        return BaseResponse.fail(exception.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse<?> businessExceptionHandler(Exception e) {
        log.error("服务内部异常：{}", e.getMessage(), e);
        return BaseResponse.fail(ErrorCodeEnum.SYSTEM_ERROR);
    }

}
